#include "connectionthread.h"
#include <QApplication>
void ConnectionThread::run(){
    m_socket = new QTcpSocket();
    m_exit = false;
    m_connected = false;
    m_alarmEvent = new bool[max_alarms];
    for(int i = 0; i < max_alarms; ++i){
        m_alarmEvent[i] = false;
    }
    while(!m_exit){
        if(m_socket->state() != QTcpSocket::ConnectedState){
            if(!tryConnectToHost()){
                continue;
            }
        }
        m_socket->write("GET /?buttonState");
        if(!m_socket->waitForBytesWritten(SOCKET_TIMEOUT)){
            emit sig_cant_connect();
            m_socket->close();
            continue;
        }
        if (!m_socket->waitForReadyRead(SOCKET_TIMEOUT)) {
            emit sig_cant_connect();
            m_socket->close();
            continue;
        }
        int by = m_socket->bytesAvailable();
        char data[20];
        if(m_socket->read(data,by) != -1){
            data[13] = 0;
            unsigned char bat = data[9];
            unsigned char otr = data[10];
            bool pwr = otr & 0x1;
            bool snd = otr & 0x2;
            unsigned char state = data[11];
            emit sig_info(bat,pwr,snd);
            for(int i = 0; i < max_alarms; ++i){
                if((state&(1<<i))){
                    if(!m_alarmEvent[i]){
                        m_alarmEvent[i] = true;
                        emit sig_event_at(i,true);
                    }
                }
                else {
                    if(m_alarmEvent[i]){
                        m_alarmEvent[i] = false;
                        emit sig_event_at(i,false);
                    }
                }
            }
        }
        else {
            m_socket->close();
            emit sig_cant_connect();
        }
        qApp->processEvents();
        msleep(100);
    }
    if(m_socket->state() != QTcpSocket::UnconnectedState){
        m_socket->close();
    }
    delete[] m_alarmEvent;
    m_alarmEvent = 0;
    delete m_socket;
    m_socket = 0;
}

ConnectionThread::~ConnectionThread(){

    //qDebug("Thread terminated");
}



ConnectionThread::ConnectionThread(const QString& ipString):
    m_socket(0),
    m_alarmEvent(0),
    m_ipString(ipString),
    max_alarms(8)
{

}

bool ConnectionThread::tryConnectToHost(){
    m_socket->connectToHost(QHostAddress(m_ipString),11111);
    if(!m_socket->waitForConnected(SOCKET_TIMEOUT)){
        if(m_connected){
            m_connected = false;
            emit sig_cant_connect();
        }
        return false;
    }
    if(!m_connected){
        m_connected = true;
        emit sig_connected();
    }
    return true;
}

void ConnectionThread::exit_thread(){
    m_exit = true;
}
